﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Data.Entity.Validation;

namespace PictureManager.Controllers
{
    public class AccountController : Controller
    {
        Models.PictrueManagerEntities context = new Models.PictrueManagerEntities();

        [AllowAnonymous]
        public ActionResult Login(string ReturnUrl)
        {
            ViewBag.消息 = context.消息.Take<Models.消息>(5);
            ViewBag.ReturnUrl = ReturnUrl;
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        public string Login(string UserID, string Password, bool RememberMe, string ReturnUrl)
        {
            if (ModelState.IsValid)
            {
                Models.用户 用户 = context.用户.FirstOrDefault(c => c.用户ID == UserID && c.密码 == Password);
                if (用户 != null)
                {
                    Models.角色 角色 = context.角色.FirstOrDefault(c => c.角色ID == 用户.角色ID);
                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, 用户.用户ID, DateTime.Now, DateTime.Now.Add(FormsAuthentication.Timeout), RememberMe, 角色.角色名称);
                    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
                    if (RememberMe)
                        cookie.Expires = DateTime.Now.AddMonths(1);
                    Response.Cookies.Add(cookie);
                    return ReturnUrl;
                }
            }
            return "Fail";
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("~/Account/Login");
        }

        [HttpPost]
        [AllowAnonymous]
        public string Register(Models.用户 entity)
        {
            if (string.IsNullOrWhiteSpace(entity.用户ID))
                return "请输入用户名";
            if (string.IsNullOrWhiteSpace(entity.密码))
                return "请输入密码";
            if (string.IsNullOrWhiteSpace(entity.姓名))
                return "请输入姓名";

            entity.角色ID = 1;
            try
            {
                context.用户.Add(entity);
                context.SaveChanges();
            }
            catch (DbEntityValidationException dbEx)
            {
                return dbEx.Message;
            }
            return "success";
        }
    }
}
